package com.kui.trytodo.stringmvc.chapter07;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
public class TestController {

    @GetMapping(value = "forward01")
    public void forward01(HttpServletRequest request, HttpServletResponse response) {
        request.setAttribute("msg", "forward01");
        try {
            request.getRequestDispatcher("/views/result.jsp").forward(request, response);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @GetMapping(value = "forward02")
    public ModelAndView forward02() {
        ModelAndView modelAndView = new ModelAndView("/views/result.jsp");
        modelAndView.addObject("msg", "forward02");
        return modelAndView;
    }

    @GetMapping(value = "forward03")
    public String forward03(HttpServletRequest request) {
        request.setAttribute("msg", "forward03");
        return "forward:/views/result.jsp";
    }

    @GetMapping(value = "forward04")
    public ModelAndView forward04() {
        ModelAndView modelAndView = new ModelAndView("result");
        modelAndView.addObject("msg", "forward04");
        return modelAndView;
    }

    @GetMapping(value = "redirect01")
    public void redirect01(HttpServletRequest request, HttpServletResponse response) {
        request.setAttribute("msg", "redirect01");
        try {
            response.sendRedirect("/chapter07/views/result.jsp");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @GetMapping(value = "redirect02")
    public String redirect02(HttpServletRequest request) {
        request.setAttribute("msg", "redirect02");
        return "redirect:/views/result.jsp";
    }

    @GetMapping(value = "redirect03")
    public ModelAndView redirect03() {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:/views/result.jsp");
        modelAndView.addObject("msg", "redirect03");
        return modelAndView;
    }


}
